package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.constants.BaseCache;
import com.bifang.module.base.core.helper.DictHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.CardEnum;
import com.jwsoft.manager.common.enums.EnrollStatusFormalEnum;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduDyjyQuerySync.DySyncResult;
import com.jwsoft.manager.common.vo.eduStudentEnroll.EduStudentEnrollVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyApplyQueryVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyApplyVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyCommonVO;
import com.jwsoft.manager.common.vo.eduSyncDyApprove.EduSyncDyApproveQueryVO;
import com.jwsoft.manager.common.vo.eduSyncDyApprove.EduSyncDyApproveVO;
import com.jwsoft.manager.common.vo.eduSyncDyEnroll.EduSyncDyEnrollKeyVO;
import com.jwsoft.manager.common.vo.eduSyncDyEnroll.EduSyncDyEnrollQueryVO;
import com.jwsoft.manager.common.vo.eduSyncDyEnroll.EduSyncDyEnrollVO;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduSyncDyApply;
import com.jwsoft.manager.core.dao.model.EduSyncDyApprove;
import com.jwsoft.manager.core.dao.model.EduSyncDyEnroll;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollService;
import com.jwsoft.manager.core.dao.service.EduSyncDyApplyService;
import com.jwsoft.manager.core.dao.service.EduSyncDyApproveService;
import com.jwsoft.manager.core.dao.service.EduSyncDyEnrollService;
import com.jwsoft.manager.core.integration.EduSyncDyApplyIntegration;
import com.jwsoft.manager.core.integration.EduSyncDyApproveIntegration;
import com.jwsoft.manager.core.integration.EduSyncDyEnrollIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import com.jwsoft.manager.core.util.dySync.CallUtils;
import com.jwsoft.manager.core.util.dySync.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.*;

/**
 * 东阳市报名专库同步情况表业务实现类
 *
 * @author wangt
 * @since 2024-06-11
 */
@ApiService(funcCode = "eduSyncDyEnroll", title = "东阳市报名专库同步情况表")
public class EduSyncDyEnrollIntegrationImpl implements EduSyncDyEnrollIntegration {

    @Autowired
    public EduSyncDyEnrollService eduSyncDyEnrollService;
    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private DictHelper dictHelper;

    @Autowired
    public EduSyncDyApplyService eduSyncDyApplyService;

    @Autowired
    public EduSyncDyApplyIntegration eduSyncDyApplyIntegration;

    @Autowired
    public EduSyncDyApproveIntegration eduSyncDyApproveIntegration;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private EduSyncDyApplyIntegration syncDyApplyIntegration;
    @Autowired
    private EduDyjyQuerySyncIntegrationImpl dyjyQuerySyncIntegration;
    @Autowired
    private EduSyncDyApproveService eduSyncDyApproveService;
    @Autowired
    private CallUtils callUtils;

    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0001", title = "东阳市报名专库同步情况表分页查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduSyncDyEnrollVO> getList(EduSyncDyEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        QueryWrapper<EduSyncDyEnroll> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(vo.getIdcard()), EduSyncDyEnroll::getIdcard, vo.getIdcard())
                .eq(EduSyncDyEnroll::getYear, eduHelper.thisYear())
                .eq(EduSyncDyEnroll::getLqSyncFlag,vo.getLqSyncFlag())
                .orderByDesc(EduSyncDyEnroll::getCreateName);
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EduSyncDyEnroll> list = eduSyncDyEnrollService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSyncDyEnroll> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSyncDyEnrollVO> resultList = Convert.toList(EduSyncDyEnrollVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(CardEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0002", title = "东阳市报名专库同步情况表根据主键查询详情", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduSyncDyEnrollVO getById(EduSyncDyEnrollKeyVO vo) {
        EduSyncDyEnroll entity = eduSyncDyEnrollService.getById(vo.getJhEnrollId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSyncDyEnrollVO result = Convert.convert(EduSyncDyEnrollVO.class, entity);
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0003", title = "东阳市报名专库同步情况表保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSyncDyEnrollVO vo) {
        //主键为空为新增校验
        if (ObjectUtils.isEmpty(vo.getIdcard())) {
            throw new AppException("用户的证件号码不能为空");
        }

    }

    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0004", title = "东阳市报名专库同步情况表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSyncDyEnroll0004",
            operationName = "东阳市报名专库同步情况表新增",
            dataType = "jhEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncDyEnrollVO add(EduSyncDyEnrollVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSyncDyApplyQueryVO eduSyncDyApplyQueryVO = new EduSyncDyApplyQueryVO();
        eduSyncDyApplyQueryVO.setIdcard(vo.getIdcard());
        eduSyncDyApplyQueryVO.setYear(eduHelper.thisYear());
        List<EduSyncDyApplyVO> listApply = eduSyncDyApplyIntegration.getList(eduSyncDyApplyQueryVO).getList();
        //校验正式库中是否存在数据
        if (CollectionUtils.isEmpty(listApply)) {
            throw new AppException("专库报名表的数据不能为空");
        }

        //
        EduSyncDyApproveVO eduSyncDyApproveVO = new EduSyncDyApproveVO();
        eduSyncDyApproveVO.setIdcard(vo.getIdcard());
        eduSyncDyApproveVO.setYear(eduHelper.thisYear());
        List<EduSyncDyApproveVO> listApprove = eduSyncDyApproveIntegration.getList(new EduSyncDyApproveQueryVO()).getList();
        if (ObjectUtils.isEmpty(listApprove)) {
            throw new AppException("专库审核表的数据不能为空");
        }



        eduSyncDyApplyQueryVO.setEnrollStatus("2");//2是已录取
        eduSyncDyApplyQueryVO.setIdcard(vo.getIdcard());
        EduSyncDyCommonVO eduSyncDyCommonVO =  eduSyncDyApplyIntegration.getListByIdCard(eduSyncDyApplyQueryVO);
        if(ObjectUtils.isEmpty(eduSyncDyCommonVO)){
            throw new AppException("正式库中不存在报名成功的数据");
        }

        EduSyncDyApplyVO apply = listApply.get(0);
        vo.setJhApplyId(apply.getJhApplyId());
        EduSyncDyEnroll entity = Convert.convert(EduSyncDyEnroll.class, vo);
        eduSyncDyEnrollService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setJhEnrollId(entity.getJhEnrollId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0005", title = "东阳市报名专库同步情况表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSyncDyEnroll0005",
            operationName = "东阳市报名专库同步情况表修改",
            dataType = "jhEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncDyEnrollVO edit(EduSyncDyEnrollVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhEnrollId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        if (ObjectUtils.isEmpty(vo.getJhApplyId())) {
            throw new AppException("传入的转库报名id不能为空");
        }
        EduSyncDyEnroll oldEntity = eduSyncDyEnrollService.getById(vo.getJhEnrollId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSyncDyEnroll entity = Convert.convert(EduSyncDyEnroll.class, vo);
        eduSyncDyEnrollService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0006", title = "东阳市报名专库同步情况表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSyncDyEnroll0006",
            operationName = "东阳市报名专库同步情况表删除",
            dataType = "jhEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSyncDyEnrollKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhEnrollId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSyncDyEnroll entity = eduSyncDyEnrollService.getById(vo.getJhEnrollId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSyncDyEnrollService.removeById(vo.getJhEnrollId());
    }

    @Override
    @OpApi(funcCode = "eduSyncDyEnroll0007", title = "批量生成同步金华库录取数据", funcType = FuncTypeEnum.insert)
    public void addBatch(EduSyncDyEnrollVO vo) {
        String redisKey = "dyedu:syncEnroll:batch";
        if (redisHelper.hasKey(redisKey)) {
            throw new AppException("正在批量处理中......");
        }
        redisHelper.set(redisKey, "1", 1800);
        try {
            if (vo.getAllFlag()==null){
                vo.setAllFlag(false);
            }
            String areaCode = vo.getApplyCountyCode();
            if (StringUtils.isBlank(areaCode)) {
                areaCode = SessionUtil.getAreaCode();
            }
            if(StringUtils.isBlank(areaCode)){
                areaCode=eduHelper.thisAreaCode();
            }
            Integer year = eduHelper.thisYear();
            List<String> enrollStatusList = new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            LambdaQueryWrapper<EduStudentEnroll> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(EduStudentEnroll::getFullName, EduStudentEnroll::getIdcard, EduStudentEnroll::getYear,
                            EduStudentEnroll::getAreaCode, EduStudentEnroll::getSchoolNature,
                            EduStudentEnroll::getSex, EduStudentEnroll::getCardType,
                            EduStudentEnroll::getSchoolCategory, EduStudentEnroll::getCreateTime, EduStudentEnroll::getBirthYmd,
                            EduStudentEnroll::getAdmitFlag, EduStudentEnroll::getAdmitRemarks, EduStudentEnroll::getAdmitTime, EduStudentEnroll::getAdmitUserId,
                            EduStudentEnroll::getSchoolId, EduStudentEnroll::getSchoolName).eq(EduStudentEnroll::getAreaCode, areaCode)
                    .eq(EduStudentEnroll::getYear, year)
                    .in(EduStudentEnroll::getEnrollStatus, enrollStatusList)
                    .inSql(EduStudentEnroll::getIdcard, "select idcard from edu_sync_dy_approve where year=" + year + " and del='0' ");
            if(vo.getAllFlag()){
                queryWrapper.notInSql(EduStudentEnroll::getIdcard, "select idcard from edu_sync_dy_enroll where year=" + year + " and del='0' ");
            }

            List<EduStudentEnroll> list = eduStudentEnrollService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                Long importBatchId = IdWorker.getId();
                Map<String, String> map = new HashMap<>();
                for (EduStudentEnroll eduStudentEnroll : list) {
                    if (map.containsKey(eduStudentEnroll.getIdcard())) {
                        continue;
                    }
                    map.put(eduStudentEnroll.getIdcard(), eduStudentEnroll.getFullName());
                    EduSyncDyEnroll eduSyncDyEnroll = new EduSyncDyEnroll();
                    QueryWrapper<EduSyncDyEnroll> enrollQueryWrapper = new QueryWrapper<>();
                    enrollQueryWrapper.lambda().select(EduSyncDyEnroll::getJhApplyId, EduSyncDyEnroll::getJhEnrollId).eq(EduSyncDyEnroll::getIdcard, eduStudentEnroll.getIdcard())
                            .eq(EduSyncDyEnroll::getYear, eduStudentEnroll.getYear())
                            .eq(EduSyncDyEnroll::getApplyCountyCode, eduStudentEnroll.getAreaCode());
                    List<EduSyncDyEnroll> enrollList = eduSyncDyEnrollService.list(enrollQueryWrapper);
                    if (!CollectionUtils.isEmpty(enrollList)) {
                        eduSyncDyEnroll.setJhEnrollId(enrollList.get(0).getJhEnrollId());
                    }
                    QueryWrapper<EduSyncDyApply> applyQueryWrapper = new QueryWrapper<>();
                    applyQueryWrapper.lambda().select(EduSyncDyApply::getJhApplyId).eq(EduSyncDyApply::getIdcard, eduStudentEnroll.getIdcard())
                            .eq(EduSyncDyApply::getYear, eduStudentEnroll.getYear())
                            .eq(EduSyncDyApply::getApplyCountyCode, eduStudentEnroll.getAreaCode());
                    List<EduSyncDyApply> applyList = eduSyncDyApplyService.list(applyQueryWrapper);
                    if (!CollectionUtils.isEmpty(applyList)) {
                        eduSyncDyEnroll.setJhApplyId(applyList.get(0).getJhApplyId());
                    }
                    eduSyncDyEnroll.setLqSyncFlag("0");
                    eduSyncDyEnroll.setYear(eduStudentEnroll.getYear());

                    eduSyncDyEnroll.setName(eduStudentEnroll.getFullName());
                    eduSyncDyEnroll.setCardType(eduStudentEnroll.getCardType());
                    eduSyncDyEnroll.setIdcard(eduStudentEnroll.getIdcard());
                    eduSyncDyEnroll.setImportBatchId(importBatchId);
                    if(BoolEnum.TRUE.getType().equalsIgnoreCase(eduStudentEnroll.getAdmitFlag())){
                        eduSyncDyEnroll.setEnrollState("1");
                    }else{
                        eduSyncDyEnroll.setEnrollState("2");
                    }
                    eduSyncDyEnroll.setSchoolCategory(eduStudentEnroll.getSchoolCategory());
                    eduSyncDyEnroll.setApplyCountyCode(eduStudentEnroll.getAreaCode());
                    eduSyncDyEnroll.setEnrollTime(eduStudentEnroll.getAdmitTime());
                    eduSyncDyEnroll.setEnrollOpinion(eduStudentEnroll.getAdmitRemarks());
                    eduSyncDyEnroll.setEnrollHuman(eduStudentEnroll.getAdmitUserId());
                    eduSyncDyEnroll.setEnrollSchoolName(eduStudentEnroll.getSchoolName());
                    eduSyncDyEnroll.setEnrollSchoolCode(eduStudentEnroll.getSchoolId());
                    eduSyncDyEnrollService.saveOrUpdate(eduSyncDyEnroll);
                }
            }

            List<String> enrollStatusNoList = new ArrayList<>();
            enrollStatusNoList.add(EnrollStatusFormalEnum.lq.getType());
            enrollStatusNoList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusNoList.add(EnrollStatusFormalEnum.dsh.getType());
            LambdaQueryWrapper<EduStudentEnroll> queryNOWrapper = new LambdaQueryWrapper<>();
            queryNOWrapper.select(EduStudentEnroll::getFullName, EduStudentEnroll::getIdcard, EduStudentEnroll::getYear,
                    EduStudentEnroll::getAreaCode, EduStudentEnroll::getSchoolNature,
                    EduStudentEnroll::getSex, EduStudentEnroll::getCardType,
                    EduStudentEnroll::getSchoolCategory, EduStudentEnroll::getCreateTime, EduStudentEnroll::getBirthYmd,
                    EduStudentEnroll::getAuthStatus,EduStudentEnroll::getAuthRemarks,EduStudentEnroll::getAuthTime,
                    EduStudentEnroll::getAdmitFlag, EduStudentEnroll::getAdmitRemarks, EduStudentEnroll::getAdmitTime, EduStudentEnroll::getAdmitUserId,
                    EduStudentEnroll::getSchoolId, EduStudentEnroll::getSchoolName).eq(EduStudentEnroll::getAreaCode, areaCode)
                    .eq(EduStudentEnroll::getYear, year)
                    .notIn(EduStudentEnroll::getEnrollStatus, enrollStatusNoList)
                    .inSql(EduStudentEnroll::getIdcard, "select idcard from edu_sync_dy_apply where year=" + year + " and del='0' ");
            List<EduStudentEnroll> nolist = eduStudentEnrollService.list(queryNOWrapper);
            if (!CollectionUtils.isEmpty(nolist)) {
                Long importBatchId = IdWorker.getId();
                Map<String, String> map = new HashMap<>();
                for (EduStudentEnroll eduStudentEnroll : nolist) {
                    if (map.containsKey(eduStudentEnroll.getIdcard())) {
                        continue;
                    }
                    map.put(eduStudentEnroll.getIdcard(), eduStudentEnroll.getFullName());
                    LambdaQueryWrapper<EduStudentEnroll> queryCanWrapper = new LambdaQueryWrapper<>();
                    queryCanWrapper.select(EduStudentEnroll::getStudentEnrollId).eq(EduStudentEnroll::getAreaCode, areaCode)
                            .eq(EduStudentEnroll::getYear, year)
                            .eq(EduStudentEnroll::getIdcard,eduStudentEnroll.getIdcard())
                            .in(EduStudentEnroll::getEnrollStatus, enrollStatusNoList);
                    if (eduStudentEnrollService.count(queryCanWrapper)>0){
                        //存在待审核或者待录取，不去处理
                        continue;
                    }
                    EduSyncDyEnroll eduSyncDyEnroll = new EduSyncDyEnroll();
                    QueryWrapper<EduSyncDyEnroll> enrollQueryWrapper = new QueryWrapper<>();
                    enrollQueryWrapper.lambda().select(EduSyncDyEnroll::getJhApplyId, EduSyncDyEnroll::getJhEnrollId).eq(EduSyncDyEnroll::getIdcard, eduStudentEnroll.getIdcard())
                            .eq(EduSyncDyEnroll::getYear, eduStudentEnroll.getYear())
                            .eq(EduSyncDyEnroll::getApplyCountyCode, eduStudentEnroll.getAreaCode());
                    List<EduSyncDyEnroll> enrollList = eduSyncDyEnrollService.list(enrollQueryWrapper);
                    if (!CollectionUtils.isEmpty(enrollList)) {
                        eduSyncDyEnroll.setJhEnrollId(enrollList.get(0).getJhEnrollId());
                    }
                    QueryWrapper<EduSyncDyApply> applyQueryWrapper = new QueryWrapper<>();
                    applyQueryWrapper.lambda().select(EduSyncDyApply::getJhApplyId).eq(EduSyncDyApply::getIdcard, eduStudentEnroll.getIdcard())
                            .eq(EduSyncDyApply::getYear, eduStudentEnroll.getYear())
                            .eq(EduSyncDyApply::getApplyCountyCode, eduStudentEnroll.getAreaCode());
                    List<EduSyncDyApply> applyList = eduSyncDyApplyService.list(applyQueryWrapper);
                    if (!CollectionUtils.isEmpty(applyList)) {
                        eduSyncDyEnroll.setJhApplyId(applyList.get(0).getJhApplyId());
                    }
                    eduSyncDyEnroll.setLqSyncFlag("0");
                    eduSyncDyEnroll.setYear(eduStudentEnroll.getYear());

                    eduSyncDyEnroll.setName(eduStudentEnroll.getFullName());
                    eduSyncDyEnroll.setCardType(eduStudentEnroll.getCardType());
                    eduSyncDyEnroll.setIdcard(eduStudentEnroll.getIdcard());
                    eduSyncDyEnroll.setImportBatchId(importBatchId);
                    if(BoolEnum.TRUE.getType().equalsIgnoreCase(eduStudentEnroll.getAdmitFlag())){
                        eduSyncDyEnroll.setEnrollState("1");
                    }else{
                        eduSyncDyEnroll.setEnrollState("2");
                    }
                    eduSyncDyEnroll.setSchoolCategory(eduStudentEnroll.getSchoolCategory());
                    eduSyncDyEnroll.setApplyCountyCode(eduStudentEnroll.getAreaCode());
                    eduSyncDyEnroll.setEnrollTime(eduStudentEnroll.getAdmitTime());
                    eduSyncDyEnroll.setEnrollOpinion(eduStudentEnroll.getAdmitRemarks());
                    eduSyncDyEnroll.setEnrollHuman(eduStudentEnroll.getAdmitUserId());
                    eduSyncDyEnroll.setEnrollSchoolName(eduStudentEnroll.getSchoolName());
                    eduSyncDyEnroll.setEnrollSchoolCode(eduStudentEnroll.getSchoolId());
                    eduSyncDyEnrollService.saveOrUpdate(eduSyncDyEnroll);
                    EduSyncDyApprove eduSyncDyApprove=new EduSyncDyApprove();
                    QueryWrapper<EduSyncDyApprove> approveQueryWrapper=new QueryWrapper<>();
                    approveQueryWrapper.lambda().select(EduSyncDyApprove::getJhApplyId,EduSyncDyApprove::getJhApproveId).eq(EduSyncDyApprove::getIdcard,eduStudentEnroll.getIdcard())
                            .eq(EduSyncDyApprove::getYear,eduStudentEnroll.getYear())
                            .eq(EduSyncDyApprove::getApplyCountyCode,eduStudentEnroll.getAreaCode());
                    List<EduSyncDyApprove> approveList=eduSyncDyApproveService.list(approveQueryWrapper);
                    if (!CollectionUtils.isEmpty(approveList)){
                        eduSyncDyApprove.setJhApproveId(approveList.get(0).getJhApproveId());
                    }
                    if (!CollectionUtils.isEmpty(applyList)){
                        eduSyncDyApprove.setJhApplyId(applyList.get(0).getJhApplyId());
                    }
                    eduSyncDyApprove.setAuditSyncFlag("0");
                    eduSyncDyApprove.setApproveHuman(eduStudentEnroll.getAuthUserId());
                    eduSyncDyApprove.setYear(eduStudentEnroll.getYear());
                    eduSyncDyApprove.setApproveTime(eduStudentEnroll.getAuthTime());
                    eduSyncDyApprove.setName(eduStudentEnroll.getFullName());
                    eduSyncDyApprove.setCardType(eduStudentEnroll.getCardType());
                    eduSyncDyApprove.setIdcard(eduStudentEnroll.getIdcard());
                    eduSyncDyApprove.setImportBatchId(importBatchId);
                    if(AuthStatusEnum.YES.getType().equalsIgnoreCase(eduStudentEnroll.getAuthStatus())){
                        eduSyncDyApprove.setApproveState("1");
                    }else{
                        eduSyncDyApprove.setApproveState("2");
                    }
                    eduSyncDyApprove.setSchoolCategory(eduStudentEnroll.getSchoolCategory());
                    eduSyncDyApprove.setApplyCountyCode(eduStudentEnroll.getAreaCode());
                    eduSyncDyApprove.setApproveOpinion(eduStudentEnroll.getAuthRemarks());
                    eduSyncDyApprove.setApproveHuman(eduStudentEnroll.getAuthUserId());
                    eduSyncDyApproveService.saveOrUpdate(eduSyncDyApprove);
                }
            }

        }catch (Exception e){
            throw new AppException("批量生成同步到金华审核库数据系统异常"+e.getMessage(),e);
        }finally {
            redisHelper.del(redisKey);
        }

    }

    @Override
    public void saveLq(EduStudentEnrollVO eduStudentEnroll) {
        EduSyncDyApply eduSyncDyApply = syncDyApplyIntegration.saveBm(eduStudentEnroll);
        QueryWrapper<EduSyncDyEnroll> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncDyEnroll::getApplyCountyCode,eduStudentEnroll.getAreaCode())
                .eq(EduSyncDyEnroll::getYear,eduStudentEnroll.getYear())
                .eq(EduSyncDyEnroll::getIdcard,eduStudentEnroll.getIdcard());
        List<EduSyncDyEnroll> eduSyncDyEnrollList = eduSyncDyEnrollService.list(queryWrapper);
        EduSyncDyEnroll eduSyncDyEnroll = new EduSyncDyEnroll();
        Long importBatchId = IdWorker.getId();
        eduSyncDyEnroll.setYear(eduStudentEnroll.getYear());

        eduSyncDyEnroll.setName(eduStudentEnroll.getFullName());
        eduSyncDyEnroll.setCardType(eduStudentEnroll.getCardType());
        eduSyncDyEnroll.setIdcard(eduStudentEnroll.getIdcard());
        eduSyncDyEnroll.setImportBatchId(importBatchId);
        eduSyncDyEnroll.setSchoolCategory(eduStudentEnroll.getSchoolCategory());
        eduSyncDyEnroll.setApplyCountyCode(eduStudentEnroll.getAreaCode());
        eduSyncDyEnroll.setEnrollTime(eduStudentEnroll.getAdmitTime());
        eduSyncDyEnroll.setEnrollOpinion(eduStudentEnroll.getAdmitRemarks());
        eduSyncDyEnroll.setEnrollHuman(eduStudentEnroll.getAdmitUserId());
        eduSyncDyEnroll.setEnrollSchoolName(eduStudentEnroll.getSchoolName());
        eduSyncDyEnroll.setEnrollSchoolCode(eduStudentEnroll.getSchoolId());
        eduSyncDyEnroll.setJhApplyId(eduSyncDyApply.getJhApplyId());

        if(!CollectionUtils.isEmpty(eduSyncDyEnrollList)){
            eduSyncDyEnroll.setJhEnrollId(eduSyncDyEnrollList.get(0).getJhEnrollId());

            if(BoolEnum.TRUE.getType().equals(eduStudentEnroll.getAdmitFlag())){
                if("1".equals(eduSyncDyEnroll.getEnrollState())&&eduSyncDyEnroll.getLqSyncFlag().equals(BoolEnum.TRUE.getType())){
                    //已录取上传，不做处理
                    return;
                }
                //录取
                eduSyncDyEnroll.setEnrollSchoolName(eduStudentEnroll.getSchoolName());
                eduSyncDyEnroll.setEnrollState("1");
                if(BoolEnum.TRUE.getType().equals(eduSyncDyApply.getBmSyncFlag())){
                    try {
                        saveSyncStudentEnrollInfo(eduSyncDyEnroll);
                        eduSyncDyEnroll.setLqSyncFlag("1");
                        eduSyncDyApply.setBmSyncRemark("录取上传成功");
                    }catch (Exception e){
                        String msg=e.getMessage();
                        if(msg.length()>300){
                            msg=msg.substring(0,200);
                        }
                        eduSyncDyEnroll.setLqSyncFlag("2");
                        eduSyncDyEnroll.setLqSyncRemark(msg);
                    }
                }
            }else {
                //不予录取
                if("2".equals(eduSyncDyEnroll.getEnrollState())&&eduSyncDyEnroll.getLqSyncFlag().equals(BoolEnum.TRUE.getType())){
                    //取消录取已同步，不做处理
                    return;
                }
                try {
                    saveSyncStudentEnrollInfo(eduSyncDyEnroll);
                    eduSyncDyEnroll.setEnrollState("2");
                    eduSyncDyEnroll.setLqSyncFlag("1");
                    eduSyncDyApply.setBmSyncRemark("取消录取上传成功");
                }catch (Exception e){
                    String msg=e.getMessage();
                    if(msg.length()>300){
                        msg=msg.substring(0,200);
                    }
                    eduSyncDyEnroll.setLqSyncFlag("2");
                    eduSyncDyEnroll.setLqSyncRemark(msg);
                }

            }
        }else {
            if(BoolEnum.TRUE.getType().equalsIgnoreCase(eduStudentEnroll.getAdmitFlag())){
                eduSyncDyEnroll.setEnrollState("1");
                try {
                    saveSyncStudentEnrollInfo(eduSyncDyEnroll);
                    eduSyncDyEnroll.setLqSyncFlag("1");
                    eduSyncDyApply.setBmSyncRemark("录取上传成功");
                }catch (Exception e){
                    String msg=e.getMessage();
                    if(msg.length()>300){
                        msg=msg.substring(0,200);
                    }
                    eduSyncDyEnroll.setLqSyncFlag("2");
                    eduSyncDyEnroll.setLqSyncRemark(msg);
                }
            }else{
                eduSyncDyEnroll.setEnrollState("2");
                try {
                    saveSyncStudentEnrollInfo(eduSyncDyEnroll);
                    eduSyncDyEnroll.setEnrollState("2");
                    eduSyncDyEnroll.setLqSyncFlag("1");
                    eduSyncDyApply.setBmSyncRemark("取消录取上传成功");
                }catch (Exception e){
                    String msg=e.getMessage();
                    if(msg.length()>300){
                        msg=msg.substring(0,200);
                    }
                    eduSyncDyEnroll.setLqSyncFlag("2");
                    eduSyncDyEnroll.setLqSyncRemark(msg);
                }
            }
        }
        eduSyncDyEnrollService.saveOrUpdate(eduSyncDyEnroll);
    }

    @Override
    public int eduJhjyLqSync(AreaControlVO vo) {
        String redisKey="dyedu:syncDyEnroll:batchSync";
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("正在批量同步金华录取数据处理中......");
        }
        redisHelper.set(redisKey,"1",1800);
        Integer year=eduHelper.thisYear();
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        QueryWrapper<EduSyncDyEnroll> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncDyEnroll::getYear, year)
                .eq(EduSyncDyEnroll::getApplyCountyCode,vo.getAreaCode())
                .eq(EduSyncDyEnroll::getEnrollState,BoolEnum.FALSE.getType());
        List<EduSyncDyEnroll> list=eduSyncDyEnrollService.list(queryWrapper);

        if (CollectionUtils.isEmpty(list)){
            QueryWrapper<EduSyncDyEnroll> queryWrapperError = new QueryWrapper<>();
            queryWrapperError.lambda().eq(EduSyncDyEnroll::getYear, year)
                    .eq(EduSyncDyEnroll::getApplyCountyCode,vo.getAreaCode())
                    .eq(EduSyncDyEnroll::getEnrollState,"2");
            List<EduSyncDyEnroll> errorList=eduSyncDyEnrollService.list(queryWrapperError);
            if(CollectionUtils.isEmpty(errorList)){
                redisHelper.del(redisKey);
                return 0;
            }
            list=errorList;
        }
        int i=0;
        for(EduSyncDyEnroll enroll:list){
            try {
                saveSyncStudentEnrollInfo(enroll);
                enroll.setLqSyncFlag("2");
                enroll.setLqSyncRemark("成功");
                eduSyncDyEnrollService.updateById(enroll);
                i++;
            }catch (AppException e){
                enroll.setLqSyncFlag("2");
                String msg=e.getMsg();
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(msg)&&msg.length()>300){
                    msg=msg.substring(0,300);
                }
                enroll.setLqSyncRemark(msg);
                eduSyncDyEnrollService.updateById(enroll);
            }catch (Exception e){
                enroll.setLqSyncFlag("2");
                String msg=e.getMessage();
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(msg)&&msg.length()>300){
                    msg=msg.substring(0,300);
                }
                enroll.setLqSyncRemark(msg);
                eduSyncDyEnrollService.updateById(enroll);
            }

        }
        redisHelper.del(redisKey);
        return i;
    }

    private void saveSyncStudentEnrollInfo(EduSyncDyEnroll vo){


        Map<String, Object> params = BeanUtil.beanToMap(vo, false, true);

        //map转string
        String paramsStr = JsonUtil.toJsonString(params);
        //将传入参数 进行签名
        String timestamp = String.valueOf(System.currentTimeMillis());
        //参数进行加密
        String appKey = dyjyQuerySyncIntegration.getCommon("dy_sync_appKey");
        String encrypt = callUtils.encrypt(paramsStr, appKey);
        //根据参数，密钥，时间生成签名
        String appSecret = dyjyQuerySyncIntegration.getCommon("dy_sync_appSecret");

        String accessToken = "";
        Cache<String,String> tokenCache = JetCacheUtils.create(BaseCache.CACHE_ACCESS_TOKEN_CLIENT, CacheType.BOTH, Duration.ofSeconds(1500L),Duration.ofSeconds(60));
        String redisKey=vo.getApplyCountyCode()+vo.getYear();
        accessToken  = tokenCache.get(redisKey);
        if (StringUtils.isBlank(accessToken)) {
            //调用获取token方法，得到token信息
            DySyncResult token = dyjyQuerySyncIntegration.getToken();
            accessToken = (String) token.getData().get("accessToken");
            tokenCache.put(redisKey, accessToken);
        }
        if (StringUtils.isBlank(accessToken)) {
            throw new AppException("accessToken不能为空");
        }
        //加密传参
        HashMap<String, String> map = new HashMap<>();
        map.put("cryptoStr", encrypt);
        String cryptoStr = JSONObject.toJSONString(map);
        String signature = callUtils.getSign(cryptoStr, appSecret, timestamp);
        if (StringUtils.isBlank(signature)) {
            throw new AppException("签名不能为空");
        }
        //调用同步删除接口
        String reqUrl = dyjyQuerySyncIntegration.getCommon("dy_sync_reqUrl");
        String appId = dyjyQuerySyncIntegration.getCommon("dy_sync_appId");
        String url = reqUrl + "syncSaveJhEnroll0001";
        String data = encrypt;
        HttpResponse execute = HttpRequest.post(url)
                //设置请求体
                .header("Content-Type", "application/json")
                .header("signature", signature)
                .header("timestamp", timestamp)
                .header("accessToken", accessToken)
                .header("appId", appId)
                .setReadTimeout(10000)
                .body(cryptoStr) //加密
                .execute();
        String body = execute.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("请求接口失败失败，未返回信息");
        }
        JSONObject jsonBody = JSONObject.parseObject(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getInteger("code") != 0) {
                if ("401".equals(jsonObject.getString("code")) || "456".equals(jsonObject.getString("code"))) {
                    //调用获取token方法，得到token信息
                    DySyncResult token = dyjyQuerySyncIntegration.getToken();
                    accessToken = (String) token.getData().get("accessToken");
                    tokenCache.put(redisKey, accessToken);
                } else {
                    String errorMessage = (String) jsonObject.get("message");
                    throw new AppException("错误原因：" + errorMessage);
                }
            }
        }catch (AppException e){
            throw new AppException(e.getMsg());
        }catch (Exception e) {
            throw new AppException("请求接口失败失败：" + body);
        }
        //密文
        String encryptResult = (String) jsonObject.get("result");
        if (StringUtils.isNotBlank(encryptResult)){
            //对密文进行解密
            String decryptResult = callUtils.decrypt(encryptResult, appSecret);
            //解密后的密文转json
            JSONObject jsoncontent = JSONObject.parseObject(decryptResult);
            //转换json
            jsonBody.put("result", jsoncontent);
        }

    }

}
